﻿using ConfExpert.Datasets.MyDataTableAdapters;
using ConfExpert.Forms.Base;

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Handler;
using DevTeam;

using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class Docs : XForm
    {
        public Docs()
        {
            InitializeComponent();
        }

        BindingSource bs;
        private void Docs_Load(object sender, EventArgs e)
        {
            
            TAM.DocsLinesTableAdapter = new DocsLinesTableAdapter();

            treeList1.OptionsSelection.EnableAppearanceFocusedCell = true;
            treeList1.OptionsBehavior.AllowIncrementalSearch = true;
            treeList1.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.ShowAlways;
            treeList1.OptionsFind.AllowFindPanel = true;
            treeList1.OptionsFind.AlwaysVisible = true;

            treeList1.OptionsBehavior.Editable = false;
            treeList1.OptionsBehavior.EnableFiltering = true;
            treeList1.OptionsView.ShowAutoFilterRow = true;
            //treeList1.FilterNode += new DevExpress.XtraTreeList.FilterNodeEventHandler(this.OnFilterNode);
            treeList1.OptionsFilter.FilterMode = DevExpress.XtraTreeList.FilterMode.Extended;
            treeList1.OptionsView.AutoWidth = false;

            GetDetails("Docs;DocsLines", "FillDocs");

            //DataSet d = ExecDataSet("FillDocs");
            treeList1.DataSource = ds.Docs; // d.Tables[0];

            //ds.DocsLines.Merge(d.Tables[1]);
            bs = gridView1.Init(ds.DocsLines);
            AddBsToList(bs);

            ds.DocsLines.TableNewRow += Docs_TableNewRow;
            gridView1.FormatAsNumber(3, "BuyuklukMB");
            gridView1.MakeColumnInvisible("DocsId", "DocsLinesId");
            gridView1.YanYanaGetir("DosyaId:DosyaAdi");
            gridView1.AddSummary();

            treeList1.ParentFieldName = "ParentId";
            treeList1.KeyFieldName = "DocsId";
            //simpleButton1.Click += simpleButton1_Click;
            treeList1.KeyDown+=treeList1_KeyDown;
            treeList1.Nodes[0].Expanded = true;
            treeList1.Nodes[0].Nodes[0].Expanded = true;
            treeList1.BestFitColumns();
            //treeList1.Nodes[1].Expanded = true;

            treeList1.FocusedNodeChanged += treeList1_FocusedNodeChanged;


            this.DragEnter += new DragEventHandler(Attachments_DragEnter);
            this.DragDrop += new DragEventHandler(Attachments_DragDrop);
            gridView1.Click += new EventHandler(gridView1_Click);

            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Aç", Ac);

            //if (AmI(4, 17, 11, 13, 14, 89, 103))
            {
                gm.GridMenu.AddMenu("Değiştir", Degistir);
                gm.GridMenu.AddMenu("Sil", Sil);

                this.AllowDrop = true;
                bbiKaydet.ItemClick += bbiKaydet_ItemClick;
                bbiSubmit.ItemClick += bbiSubmit_ItemClick;
                bbiEkle.ItemClick += bbiEkle_ItemClick;
            }
            //else
            //    bbiKaydet.Enabled = false;

            gridView1.MakeReadOnly("Aciklama");

            //gridView1.ShowingEditor += new System.ComponentModel.CancelEventHandler(gridView1_ShowingEditor);
            //gridView1.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gridView1_RowStyle);
            gridView1.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gridView1_RowCellStyle);
            //gridView1.Columns["ModifiedOn"].Caption = "Eklenme Tarihi";
            //gridView1.Columns["ModifiedOn"].Visible = true;

            gridView1.BestFitColumns();
            gridView1.ShowFindPanel();

            treeList1.NodeCellStyle+=treeList1_NodeCellStyle;
            FolderName = Path.Combine(Path.GetTempPath(), "\\CEDocs");
            bbiSubmit.Enabled = !IsDirectoryEmpty(FolderName);
            splitContainerControl1.AutoSize();
        }

        string FolderName;
        void bbiEkle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (DocsNode dn = new DocsNode(DocsId))
                if (dn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    if (dn.dt != null)
                    {
                        ds.Docs.Merge(dn.dt);
                        treeList1.RefreshDataSource();
                    }
        }

        void bbiSubmit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string FullPath = FileManager.GetTempFolder("CEDocs");
            foreach (string filePath in Directory.GetFiles(FullPath, "*.*", SearchOption.AllDirectories))
            {
                FileInfo fi = new FileInfo(filePath);
                
                byte[] bArr = FileManager.Read(fi.FullName);
                string[] FN = fi.Name.Split(".".ToCharArray());

                GetDetails("DocsLines", "UpdDoc", FN[0].ToInt(), fi.Name.Substring(FN[0].Length + 1), fi.Extension, bArr, WhoAmI, "Arşiv", 0);
                File.Delete(fi.FullName);
            }

            gridView1.BestFitColumns();
            bbiSubmit.Enabled = !IsDirectoryEmpty(FolderName);
        }


        public bool IsDirectoryEmpty(string path)
        {
            return !Directory.EnumerateFileSystemEntries(path).Any();
        }

        void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            Save();
        }



        void gridView1_Click(object sender, EventArgs e)
        {
            GridHitInfo hi = gridView1.CalcHitInfo(gridControl1.PointToClient(MousePosition));
            if ((hi.InRow || hi.InRowCell) && gridView1.FocusedRowHandle > -1)
                if (gridView1.FocusedColumn.FieldName == "Ext")
                {
                    //Guid ID = (Guid)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DosyaId");
                    int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));
                    if (DosyaId > 0)
                    {
                        txtInfo.Caption = gridView1.GetFocusedRowCellDisplayText("DosyaAdi");
                        DataTable dc = ExecuteDataTable("GetDoc", DosyaId);
                        
                        string FileName  = "CEDocs\\" + DosyaId.ToString() + "." + dc.Rows[0]["DosyaAdi"].ToString();
                        byte[] bytes = dc.Rows[0]["BLOB"] as byte[];
                        FileManager.RunTempFile(FileName, bytes);
                         
                    }
                }

            bbiSubmit.Enabled = !IsDirectoryEmpty(FolderName);

        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle == view.FocusedRowHandle)
                e.Appearance.BackColor = Color.YellowGreen; // SystemColors.ControlDark;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

            if (e.Column.FieldName == "Ext")
            {
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                e.Appearance.ForeColor = Color.DarkOrchid;
            }
        }


        void Attachments_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            foreach(string file in files)
            {
                FileInfo fi = new FileInfo(file);

                byte[] bArr = FileManager.Read(fi.FullName);
                
                GetDetails("Docs;DocsLines", "AddDoc", DocsId, fi.Name, fi.Extension, bArr, WhoAmI, "Arşiv", 0);
            }
            gridView1.BestFitColumns();
        }

        void Attachments_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                e.Effect = DragDropEffects.All;
        }



        void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (gvListe.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            e.Cancel = (intParse(gridView1.GetFocusedRowCellValue("UserId")) != WhoAmI);
            //e.Cancel = (gvCounting.GetRowCellValue(gvCounting.FocusedRowHandle, "isReadOnly").ToString() == bool.TrueString);
        }
        

        private void Degistir(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("DosyaId") != null)
            {
                int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (openFileDialog1.OpenFile() != null)
                        {
                            
                            
                            FileInfo fi = new FileInfo(openFileDialog1.FileName);
                            //fi.LastWriteTime

                            byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                            GetDetails("DocsLines", "UpdDoc", DosyaId, fi.Name, fi.Extension, bArr, WhoAmI, "Arşiv", 0);
                            gridView1.BestFitColumns();
                            Notify("Dosya güncellendi.");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        private void treeList1_NodeCellStyle(object sender, GetCustomNodeCellStyleEventArgs e)
        {
            if (e.Column.FieldName != "Name") return;
            //if (Convert.ToInt32(e.Node.GetValue(e.Column.AbsoluteIndex)) > 500000)
            if(e.Node.GetValue(treeList1.Columns["Tarih"])==DBNull.Value)
            {
                //e.Appearance.BackColor = Color.FromArgb(80, 255, 0, 255);
                //e.Appearance.ForeColor = Color.White;
                e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
            }
        }

        private void Sil(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("DosyaId") != null)
                if (XtraMessageBox.Show("Emin misiniz?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    int DosyaId = intParse(gridView1.GetFocusedRowCellValue("DosyaId"));

                    GetDetails("Docs", "DelDoc", DosyaId);

                    gridView1.DeleteRow(gridView1.FocusedRowHandle);
                    Save();
                    Notify("Dosya silindi.");
                }
        }

        private void Ac(object sender, EventArgs e)
        {
            gridView1_Click(null, null);
        }

        void Docs_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["DocsId"] = DocsId;
        }

        int DocsId = 0;
        void treeList1_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            DocsId = e.Node.GetValue("DocsId").ToInt();
            bs.Filter = "DocsId=" + DocsId.ToString();
            gridView1.BestFitColumns();
        }


        private void treeList1_KeyDown(object sender, KeyEventArgs e)
        {
            TreeListHandler Handler = typeof(TreeList).GetProperty("Handler", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(treeList1, null) as TreeListHandler;
        }
       

        //    /*
        //    treeList1.Nodes.Clear();
        //    treeList1.DataSource = dt;
        //    treeList1.ParentFieldName = "ParentId";
        //    treeList1.KeyFieldName = "DocsId";
        //    //treeList1.OptionsView.ShowVertLines = true;
        //    //treeList1.OptionsView.ShowFocusedFrame = true;
        //    //treeList1.OptionsView.ShowButtons = true;
        //    //treeList1.OptionsFind.AllowFindPanel = true;
        //    treeList1.OptionsView.ShowAutoFilterRow = true;
        //    treeList1.OptionsBehavior.EnableFiltering = true;
        //    treeList1.OptionsFilter.FilterMode = DevExpress.XtraTreeList.FilterMode.Extended;
        //    */


    }
}
